#include "raster_camera.h"
#include "settings.h"
#include "sdl_screen.h"


RasterCamera::RasterCamera(const glm::vec3& pos, float focal)
: Camera(pos, focal)
, _shader(this)
{
	sdl::Event::getInstance()->addListener(this);
}


void RasterCamera::VertexShader::transform(const glm::vec3& in, glm::vec3* out) const
{
	sdl::Screen* s = sdl::Screen::getInstance();
	const glm::vec3& p = (in - _cam->getWorldPos()) * _cam->getRotYMatrix();
	float f = _cam->getFocalLength();

	out->x = round(f * p.x / p.z + s->getWidth() / 2.f);
	out->y = round(f * p.y / p.z + s->getHeight() / 2.f);
	out->z = (in * _cam->getRotYMatrix()).z;
//	out->z = in.z;
}


void RasterCamera::on(EventListener::KeyPressed, const Uint8* key) throw()
{
	// Make it possible to press two keys simultaneously
	bool redraw = false;

	if (key[CAMERA_MOVE_FORW]) {
		// Move camera forward
		transform(glm::vec3(0, 0, CAMERA_MOVE_STEP));
		redraw = true;
	}
	else if (key[CAMERA_MOVE_BACK]) {
		// Move camera backward
		transform(glm::vec3(0, 0, -CAMERA_MOVE_STEP));
		redraw = true;
	}
	if (key[CAMERA_MOVE_LEFT]) {
		// Move camera to the left
		rotateY(CAMERA_ROTATE_ANGLE);
		redraw = true;
	}
	else if (key[CAMERA_MOVE_RIGHT]) {
		// Move camera to the right
		rotateY(-CAMERA_ROTATE_ANGLE);
		redraw = true;
	}

	if (redraw) {
		// Update screen
		sdl::Screen::getInstance()->update();
	}
}

